<template>
  <ul class="legend">
    <li v-for="earning in data.income" :key="earning.interval">{{ earning.interval }}</li>
  </ul>
  <div ref="container" style="height: 200px"></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
const props = defineProps({
  data: {
    type: Object as PropType<EarningsData>,
    required: true
  }
});
const container = ref(null);
let myChart: any;
interface EarningsData {
  county: string;
  income: {
    interval: string;
    number: number;
  }[];
}

function initChart(data: EarningsData) {
  if (!myChart) {
    myChart = echarts.init(container.value);
  }
  const colors = ['#008CFF', '#14CC8F', '#6C7EE4', '#E76D36', '#FF930F', '#17B4BF'];
  const option = {
    color: colors,
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: data.income.map((d) => d.interval),
      axisLine: {
        lineStyle: {
          color: '#4768A9'
        }
      },
      axisLabel: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    grid: {
      top: 25,
      right: 20,
      bottom: 20,
      left: 48
    },
    yAxis: {
      axisLine: {
        lineStyle: {
          color: '#C9CDD4'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#19ECFF44',
          type: 'dashed'
        }
      },
      type: 'value'
    },
    series: [
      {
        name: '各地区人群收入情况',
        type: 'bar',
        data: data.income.map((d, i) => ({
          name: d.interval,
          value: d.number,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: colors[i] },
              { offset: 1, color: colors[i] + '22' }
            ])
          }
        })),
        barWidth: 22
      }
    ]
  };
  myChart.setOption(option);
}
watch(
  () => props.data,
  (val) => {
    if (val) {
      initChart(val);
    }
  }
);
onMounted(() => {
  if (props.data) {
    initChart(props.data);
  }
});
</script>

<style lang="scss" scoped>
.legend {
  display: flex;
  justify-content: space-between;
  padding: 20px 16px 0;

  li {
    display: flex;
    align-items: center;
    color: #e6f7ffb3;
    font-size: 12px;
    font-weight: 400;

    &::before {
      content: '';
      margin-right: 2px;
      width: 8px;
      height: 8px;
      background-color: #008cff;
    }

    $colors: #008cff, #14cc8f, #6c7ee4, #e76d36, #ff930f, #17b4bf;
    $length: length($colors);

    @for $i from 1 through $length {
      &:nth-child(#{$i}) {
        &::before {
          background-color: nth($colors, $i);
        }
      }
    }
  }
}
</style>
